package com.siterwell.push.service.impl;

import com.siterwell.push.dao.DeviceDao;
import com.siterwell.push.dao.RelationDao;
import com.siterwell.push.entity.TouristRelation;
import com.siterwell.push.service.IDeviceService;
import com.siterwell.push.util.ReadUtil.FCMManager;
import net.thxjj.sitermodel.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeviceService implements IDeviceService {

    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private RelationDao relationDao;

    @Override
    public List<Device> getAllDeviceList() {
        return deviceDao.getAllDeviceList();
    }

    @Async("asyncExecutor")
    @Override
    public void insertGateway(Device device) {
          Device device1 =  deviceDao.getDeviceInfo(device.getDeviceId());
          if(device1==null){
              deviceDao.saveSingleDevice(device);
          }
    }



    @Override
    public List<String> getRelations(String deviceId) {
        List<TouristRelation> list = relationDao.getRelationList(deviceId);
        List<Long> list_long = new ArrayList<>();
        for (TouristRelation t:
             list) {
            list_long.add(t.getRegisterId());
        }

        if(list_long.size()>0){
            return relationDao.getFCMregisterTokens(list_long);
        }else{
            return new ArrayList<>();
        }

    }


    @Async("asyncExecutor")
    @Override
    public void sendFCMMessage(String registerToken, String title, String content) {
        try {
            new FCMManager(title,content,registerToken).sendCommonMessage();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
